/** @format */

import { resultsModel } from '../../../sdk'
import { CODE_TYPES } from '../../../errorCode'
import { DRAW_STATUS, PRIZE_TYPE } from '../../../constants'
import { dbFindOne } from '../mongodb'
import { AWARDS_DB_NAME } from '../../../db'
import { getAwardValidTime } from '../../custom/getAwardValidTime'

export default function checkValidPrize(prizeTypes: number[]) {
  return async (context: IContext<{ id: string }>, { activityInfo }: IControllerInfos) => {
    const { id } = context.data
    let awardInfo = await dbFindOne<IAwards>(context, AWARDS_DB_NAME, {
      _id: id
    })
    console.log(`receive-award`, awardInfo)
    // 奖品不存在
    if (!awardInfo) {
      return resultsModel.error(CODE_TYPES.ERROR_NO_PRIZE)
    }
    // 不是校验的奖品类型，非法操作
    if (!prizeTypes.includes(awardInfo.type)) {
      return resultsModel.error(CODE_TYPES.ERROR_FORBIDDEN_OPE)
    }

    // 状态不是1,6
    if (![DRAW_STATUS.WAITAWARD, DRAW_STATUS.RETRY].includes(awardInfo.drawStatus)) {
      return resultsModel.error(CODE_TYPES.ERROR_FORBIDDEN_OPE)
    }

    // 若有过期时间，且已过期
    if (Date.now() > getAwardValidTime(activityInfo, awardInfo)) {
      return resultsModel.error(CODE_TYPES.ERROR_PRIZE_EXPIRED)
    }

    return {
      awardInfo
    }
  }
}

export const checkValidObjectPrize = checkValidPrize([PRIZE_TYPE.OBJECT])

export const checkValidEnamePrize = checkValidPrize([PRIZE_TYPE.ENAME, PRIZE_TYPE.CREDITS])
